export function isImageByMIME(type) {
  return type && type.startsWith('image/')
}

export function isImageByExtension(name) {
  // 常见图片扩展名白名单
  const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'svg'];
  const fileName = name.toLowerCase();
  const extension = fileName.split('.').pop();
  return imageExtensions.includes(extension);
}

/**
 * 文件大小单位转换函数
 * @param {number} bytes - 文件字节数
 * @param {number} [decimals=2] - 保留小数位数
 * @returns {string} 格式化后的字符串
 */
export function formatFileSize(bytes, decimals = 2) {
  if (bytes <= 0) return '0 B'

  const units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
  const unitIndex = Math.floor(Math.log(bytes) / Math.log(1024))
  const size = bytes / Math.pow(1024, unitIndex)

  return `${parseFloat(size.toFixed(decimals))} ${units[unitIndex]}`
}

export function getFileExtension(fileName) {
  const lastDotIndex = fileName && fileName.lastIndexOf('.') || -1
  return lastDotIndex === -1 ? '' : fileName.slice(lastDotIndex + 1).toUpperCase()
}

export function OmitFileExtension(fileName) {
  const lastDotIndex = fileName && fileName.lastIndexOf('.') || -1
  return lastDotIndex === -1 ? '' : fileName.slice(0, lastDotIndex)
}

export function fileUrlParse(url) {
  // return url.replace('D:\\data\\pic', process.env.VUE_APP_BASE_HOST).replace(/\\/g, '/')
  return url.replace('D:\\data\\pic', process.env.VUE_APP_BASE_HOST)
}

export function triggerDownload(url, filename) {
  const link = document.createElement('a');
  link.href = url;
  link.target = '_blank'
  link.download = filename || 'file';
  link.style.display = 'none';
  document.body.appendChild(link);
  link.click();
  window.setTimeout(() => {
    document.body.removeChild(link);
  }, 50);
}